<?php
/**
 * Created by PhpStorm.
 * User: HS032
 * Date: 2020/8/22
 * Time: 14:14
 */

namespace ticket\modules\backend\controllers;


use ticket\libs\Tools;
use ticket\libs\Zhiyoubao\Zhiyoubao;
use ticket\modules\backend\models\OrderInfo;
use ticket\modules\backend\models\TicketInfo;
use ticket\modules\backend\models\TicketOrderSearch;
use ticket\modules\frontend\models\ErrorMsg;
use Yii;

/*** 门票订单
 * Class TicektOrderController
 * @package ticket\modules\backend\controllers
 */
class TicketOrderController extends BasicController
{

    /*** 门票订单信息列表
     * @return false|string
     */
    public function actionTicketOrderList()
    {
        $get = Yii::$app->request->get();
        $page = isset($get['page'])?$get['page']:1;
        $pageSize = isset($get['size'])?$get['size']:10;

        $aid = $this->appId;
        if (empty($aid)){
            return Tools::showRes(10007,'请登录');
        }
        $searchModel = (new TicketOrderSearch())->search($get)->andWhere(['app_id' => $aid]);
        $count = $searchModel->count();
        $orderList = $searchModel->offset($pageSize * ($page - 1))->orderBy(['oid' => SORT_DESC])->limit($pageSize)->asArray()->all();

        foreach ($orderList as $key => $val){
            if ($val['order_status'] == 3 and $val['is_finish'] == 2){
                $orderList[$key]['order_status'] = 5;
            }
            $orderList[$key]['order_amount'] = $val['order_amount']/100;
            $orderList[$key]['real_pay'] = $val['real_pay']/100;
            if (!empty($val['pay_note'])){
                $orderList[$key]['pay_note'] = json_decode($val['pay_note']);
            }
        }


        return Tools::showRes(0,'success',[
            'orderList' => $orderList,
            'page' => $page,
            'size' => $pageSize,
            'count' => $count,
        ]);
    }


    /*** 获取订单详情
     * @return false|string
     */
    public function actionTicketOrderInfo()
    {
        $get = Yii::$app->request->get();
        $oid = isset($get['oid'])?$get['oid']:'';
        if (empty($oid)){
            return Tools::showRes(99,'参数有误');
        }
        $searchModel = OrderInfo::find()->where(['tk_order_info.oid' => $oid]);
        $orderInfo = $searchModel->joinWith(['details'])->asArray()->one();
        if (empty($orderInfo)){
            $orderInfo = [];
        }else{
            $orderInfo['order_amount'] = $orderInfo['order_amount']/100;
            $orderInfo['real_pay'] = $orderInfo['real_pay']/100;
        }
        $orderLog = $this->orderLog($orderInfo['pay_number']);
        return Tools::showRes(0,'success',[
            'orderInfo' => $orderInfo,
            'orderLog' => $orderLog,
        ]);

    }


    /*** 修改订单状态->异常
     * @return false|string
     */
    public function actionUpdateOrder()
    {
        if (Yii::$app->request->isPost){
            $post = Yii::$app->request->post();
            $oid = isset($post['oid'])?$post['oid']:'';
            if (empty($oid)){
                return Tools::showRes(10404,'参数有误');
            }

            $orderInfoModel = new OrderInfo();
            if ($orderInfoModel->updateOrder($oid)){
                return Tools::showRes(0,'修改成功');
            }
            return Tools::showRes(10405,'修改失败');
        }
    }

    /*** 手动修改门票订单为已退款状态
     * @return false|string
     */
    public function actionRefundOrder()
    {
        if (Yii::$app->request->isPost){
            $post = Yii::$app->request->post();
            $oid = isset($post['oid'])?$post['oid']:'';
            if (empty($oid)){
                return Tools::showRes(10404,'参数有误');
            }

            $orderInfoModel = new OrderInfo();
            if ($orderInfoModel->RefundOrder($oid)){
                return Tools::showRes(0,'修改成功');
            }
            return Tools::showRes(10405,'修改失败');
        }
    }

    /*** 判断是否有订单异常
     * @return false|string
     */
    public function actionIsOrderAbnormal()
    {
        if (Yii::$app->request->isPost){
            $aid = $this->appId;
            if (empty($aid)){
                return Tools::showRes(10007,'请登录');
            }
            if ($aid == 1){
                $nowTime = date("Y-m-d H:i:s",time());
                $befTime = date("Y-m-d H:i:s",strtotime('-30 day'));

                $query = OrderInfo::find()->where(['aid' => $aid,'order_status' => 3,'is_finish' => 2]);
                $query->andFilterWhere(['between','pay_time',$befTime,$nowTime]);
                $count = $query->count();
                if ($count > 0){
                    return Tools::showRes(0,'有'.$count.'笔订单异常请及时处理');
                }
            }
            return Tools::showRes(300,'暂无异常');
        }
    }


    public function actionSendPlaceOrder()
    {
        if  (Yii::$app->request->isPost){
            $orderSn = Yii::$app->request->post('orderSn','');
            $paySn = Yii::$app->request->post('paySn','');
            if (empty($orderSn) || empty($paySn)){
                return Tools::showRes(300,'参数有误');
            }

            $orderModel = new OrderInfo();
            $query = $orderModel->getDetail($paySn)->one();
            if ($query->order_status == 1 || $query->is_finish != 2){
                return Tools::showRes(300,'订单未支付或已下单成功');
            }
//            $res = $this->sendTicketUser($orderSn);
            $params = $this->getParams($orderSn,$paySn);  // 封装参数
            $zhiyoubao = new Zhiyoubao($params['aid']);
            // 门票下单
            $result = $zhiyoubao->getPlaceOrder($params);  // 下单
            if (!$result){
                return Tools::showRes(300,'发送失败');
            }
            OrderInfo::updateAll(['is_finish' => '1','order_status' => 3],['pay_number' => $paySn]);
            return Tools::showRes(0,'发送成功');
        }
    }


    protected function orderLog($pay_number)
    {
        if (empty($pay_number)){
            return [];
        }

        $errorMsgModel = new ErrorMsg();
        $info = $errorMsgModel->getDetails($pay_number);
        return $info;
    }


    protected function getParams($orderSn,$payOrderSn)
    {
        $orderInfo =  OrderInfo::find()->where('tk_order_info.order_number = :osn',[':osn' => $orderSn])->
        joinWith(['detailes'])->asArray()->one();
        $ticketInfo = TicketInfo::find()->where('tid = :id',[':id' => $orderInfo['tid']])->select(['ticket_sn','now_ticket_sn'])->asArray()->one();
        $ticketSn = $ticketInfo['ticket_sn'];
        // 预定时间是今天
        if (date("Y-m-d") == date("Y-m-d",strtotime($orderInfo['detailes']['reserve_time']))){
            if (!empty($ticketInfo['now_ticket_sn'])){
                $ticketSn = $ticketInfo['now_ticket_sn'];
            }
        }
        $params = [
            'certificate' => $orderInfo['detailes']['certificate'],  // 身份证号
            'name' => $orderInfo['detailes']['name'],
            'phone' => $orderInfo['detailes']['phone'],
            'order_sn' => $payOrderSn,
            'num' => $orderInfo['detailes']['ticket_num'],
            'price' => $orderInfo['order_amount']/100,
            'unit_price' => $orderInfo['detailes']['price'],
            'ticket_sn' => $ticketSn,
            'goods_name' => str_replace('+','',$orderInfo['goods_name']),// str_replace('+','',$orderInfo['goods_name']);
            'describe' => '',
            'reserveTime' => date("Y-m-d",strtotime($orderInfo['detailes']['reserve_time'])),
            'aid' => $orderInfo['aid'],
            'orderDetailsId' => $orderInfo['detailes']['id'],
        ];
        return $params;
    }
}